﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using VteamProjectAssistant.Constants;

namespace VteamProjectAssistant.SettingWindow
{

    public class SvnAuthenticationInfo
    {
        [JsonPropertyName("username")]
        public string? Username { get; set; }

        [JsonPropertyName("password")]
        public string? Password { get; set; }
    }

    public partial class SettingWindowViewModel : ObservableObject
    {

        private readonly IMessenger _messenger;

        [ObservableProperty]
        private string? oldSvnUserName;

        [ObservableProperty]
        private string? oldSvnPassword;

        [ObservableProperty]
        private string? _svnUserName;

        [ObservableProperty]
        private string? _svnPassword;

        [ObservableProperty]
        private bool _canSave;

        public SettingWindowViewModel(IMessenger messenger)
        {
            _messenger = messenger;

            List<string> listenFieldList = new List<string> { nameof(SvnUserName), nameof(SvnPassword) };
            PropertyChanged += (sender, e) =>
            {
                if (listenFieldList.Contains( e.PropertyName!.Trim()))
                {
                    CanSave = SvnUserName != OldSvnUserName || SvnPassword != OldSvnPassword;
                }
            };
            CanSave = false;
        }

        [RelayCommand]
        private void LoadAuthenticationInfo()
        {
            string userHome = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string configFileName = "project_assistant_config.json";
            // 组合完整路径
            string configFilePath = Path.Combine(userHome, configFileName);

            if (File.Exists(configFilePath))
            {
                var content = File.ReadAllText(configFilePath);
                if (null != content && content.Length > 0 && content.StartsWith("{") && content.EndsWith("}"))
                {
                    SvnAuthenticationInfo svnAuthenticationInfo = JsonSerializer.Deserialize<SvnAuthenticationInfo>(content)!;
                    OldSvnUserName = svnAuthenticationInfo.Username!;
                    OldSvnPassword = svnAuthenticationInfo.Password!;
                    SvnUserName = svnAuthenticationInfo.Username!;
                    SvnPassword = svnAuthenticationInfo.Password!;
                }
            }
        }

        [RelayCommand]
        private void SaveSvnAuthenticationInfo()
        {
            string userHome = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string configFileName = "project_assistant_config.json";
            // 组合完整路径
            string configFilePath = Path.Combine(userHome, configFileName);

            var config = new Dictionary<string, string>();
            config.Add("username", SvnUserName!);
            config.Add("password", SvnPassword!);
            // 序列化配置对象为JSON字符串
            string jsonString = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(configFilePath, jsonString);
            _messenger.Send(new ValueChangedMessage<string>(SvnUserName!), MessageEventTokenConstant.UPDATE_SVN_USER_NAME);
        }

        [RelayCommand]
        private void RevertSvnAuthenticationInfo()
        {
            SvnUserName = OldSvnUserName;
            SvnPassword = OldSvnPassword;
        }
    }
}
